<template>
    <div class="w750 white-bg" v-if="!oauthLoginStatus2">
        <!-- <header>
            <div class="header-box">
                <div class="header-back" @click="goback">
                    <span class="back-img"><img src="../../assets/images/back.png" alt="" /></span>
                </div>
                <div class="header-search"><p class="ser-txt">登录中心</p></div>
                <div class="header-mes"></div>
            </div>
        </header> -->

        <div class="captcha">
            <div class="login" :class="themes.theme">
                <div class="container">
                    <h3>{{ !loginMode ? '验证码绑定' : '帐号密码绑定' }}</h3>
                    <p class="safe-tips">为了你的帐号安全，请用手机号绑定</p>
                    <!-- 验证码 -->
                    <div class="login-box">
                        <div class="country">中国 +86</div>
                        <div class="phone cell">
                            <div class="field__body">
                                <input type="text" maxlength="11" placeholder="请输入手机号码" v-model="phone" />
                            </div>
                        </div>
                    </div>
                    <div class="login-box" v-show="!loginMode">
                        <div class="phone cell">
                            <div class="field__body">
                                <input type="text" maxlength="6" placeholder="请输入6位验证码" v-model="code" />
                            </div>
                            <getvali-date codeType="bindPhone" :codeMobile="phone" :class="'login-btn'" @sendCode="getInvRelationShipSetting" />
                        </div>
                    </div>
                    <div class="login-box" v-show="loginMode">
                        <div class="phone cell">
                            <div class="field__body">
                                <input type="password" placeholder="请输入密码" v-model="password" />
                            </div>
                        </div>
                    </div>
                    <div class="font-14" v-if="inviteSetting.registerNeedInviter && !inviteSetting.hasInvitationRelationship && !inviteSetting.oldUser">
                        <div class="pb-1 pt-2 border-bottom d-flex">
                            <span class="text-999">邀请码：</span>
                            <input class="flex-1" type="text" placeholder="请输入邀请码" v-model="inviteCode" />
                        </div>
                        <div class="d-flex a-center font-12 py-1" v-if="inviteSetting.defaultInvitationCode">
                            <span class="flex-1">备选邀请码：{{ inviteSetting.defaultInvitationCode }}</span>
                            <span class="bg-main text-fff p-1 rounded-6" @click="fillInviteCode">一键填入</span>
                        </div>
                    </div>

                    <div class="b-btn" style="margin-top: 20px; padding: 5px 0px" @click.prevent="login"><span class="btn-r">登录</span></div>
                    <p class="checke-type clearfix">
                        <span class="pass-btn" @click="dealLoginMode(loginMode)">{{ !loginMode ? '密码绑定' : '验证码绑定' }}</span>
                        <!-- <span class="register-btn" @click.prevent="goRegister">免费注册</span> -->
                        <span class="forget-pass-btn" v-if="loginMode" @click="goForgetPsw">设置密码</span>
                    </p>
                </div>
            </div>
			
			<div class="go-home flex-center" @click="backHome">
				<svg class="icon svg-icon" style="width: 27px; height: 27px;" aria-hidden="true">
					<use xlink:href="#iconhomePage"></use>
				</svg>
			</div>

            <!-- 暂时不用做这么多第三方登录，所以注释掉 -->
            <!-- <div class="other-login">
				<div class="other-tit"><span class="tit-span">第三方账号登录</span></div>
				<div class="other-way">
					<span class="item" @click="oauthLogin('qq')"><img src="../../assets/images/qq-login.png" alt=""/></span>
					<span class="item" @click="oauthLogin('weixin')" v-if="isApp"><img src="../../assets/images/wx-login.png" alt=""/></span>
					<span class="item" @click="oauthLogin('sinaweibo')"><img src="../../assets/images/wb-login.png" alt=""/></span>
				</div>
			</div> -->

            <!-- <div class="login__footer">
                登录即代表同意
                <span @click="goAgreement">《用户注册协议》</span>
            </div> -->
        </div>
    </div>
</template>

<script>
import getvaliDate from 'components/getvaliDate/getvaliDate'
import { passport } from 'utils/Cache'
import formCheck from 'utils/formCheck'
import { mapState } from 'vuex'
import oauthService from 'service/oauth'
import oauthApi from 'api/login'
import { InvRelationShipSetting, bindUserMobile } from 'api/my'

export default {
    components: {
        getvaliDate
    },
    data() {
        return {
            loginMode: true, // 登陆方式, true密码登陆, false 验证码登录
            userName: '', // 手机号码，或者用户名，邮箱
            password: '', //密码
            phone: '', // 手机号码
            code: '', //验证码
            countDown: 0, // 倒计时
            passportIdKey: passport.getPassportIdKey(), //第三方登录通过后的通行证密钥
            isApp: window.plus, //当是app端时，才显示第三方登录按钮
            oauthLoginStatus2: false, //如果不加这个，会出现点击第三方登录后，再跳转到手机绑定时，会先跳到该页面影响用户体验
            inviteCode: '', // 邀请码
            inviteSetting: {} // 邀请关系配置
        }
    },
    mounted() {
        this.oauthLoginStatus2 = false
    },
    methods: {
        //返回
        goback() {
            // this.$router.back();
            // this.$router.isBack = true;
            this.$router.replace('/index')
        },

        //前往注册
        goRegister() {
            this.$router.push('/register')
        },

        //前往找回密码
        goForgetPsw() {
            this.$router.push({path: '/forgetPsw', query: {title:'设置密码'}})
        },

        // 登陆模式切换
        dealLoginMode(flag) {
            this.loginMode = !flag
            this.countDown = 0
            clearInterval(this.intervalId)
        },

        // 判断补充个人信息
        getSetupInfo() {
            return new Promise((resolve, reject) => {
                oauthApi
                    .needSetupInfo()
                    .then((res) => {
                        if (!res.success) {
                            reject(res)
                        }
                        resolve(res)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },

        //登录
        async login() {
            if (this.loginMode) {
                //如果是账号密码登录
                let errorMsg =
                    formCheck.isNonEmpty(this.phone, '请输入手机号') ||
                    formCheck.phoneRight(this.phone, '请输入正确的手机号码') ||
                    formCheck.isNonEmpty(this.password, '请输入正确密码') ||
                    formCheck.isEqual(this.newPwd, this.surePwd, '两次密码不一致')

                if (errorMsg) {
                    this.$toast(errorMsg)
                    return
                }

                //账号密码登录
                this.$toast.loading({
                    message: '登录中...',
                    forbidClick: true
                })
				
                //调用登录
                try {
                    let res = await oauthService.loginWechat(this.phone, this.password, this.passportIdKey, 'NORMAL')

                    if (!res.success) {
                        this.$toast(res.msg)
                        return
                    }

                    this.$toast({
                        message: '登录成功',
                        forbidClick: true
                    })

                    // 判断是不是有绑定qrCode
                    const qrCode = sessionStorage.getItem('qrCode')
                    if (qrCode) {
                        oauthApi
                            .bindRelationshipByQRCode({
                                qrCodeNumber: qrCode
                            })
                            .then((res) => {
                                if (!res.success) {
                                    this.$toast(res.msg)
                                    return
                                }
                                sessionStorage.removeItem('qrCode')
                            })
                            .catch((err) => {
                                sessionStorage.removeItem('qrCode')
                            })
                    }

                    // 判断用户是否需要立即补充用户信息
                    try {
      //                   const response = await this.getSetupInfo()
						// this.$store.commit('setupInfo', response);
						this.$store.dispatch('setupInfo');
						let response = this.$store.state.curUpInfo
                        if (response.result) {
                            this.$dialog
                                .confirm({
                                    title: '提示',
                                    showCancelButton: false,
                                    message: '您未完善个人信息，请前往完善个人信息'
                                })
                                .then(() => {
                                    this.$router.replace({ name: 'security', query: { need: 'finish', redirect: this.$route.query.redirect } })
                                })
                                .catch(() => {
                                    // on cancel
                                })
                        } else {
                            if (this.$route.query.redirect) {
                                this.$router.replace({ path: this.$route.query.redirect })
                            } else {
                                this.$router.replace('index')
                            }
                        }
                    } catch (err) {
                        this.$toast(error.msg)
                    }
                } catch (error) {
                    this.$toast({
                        message: error.msg
                    })
                }
            } else {
                //如果是快捷登录

                let errorMsg =
                    formCheck.isNonEmpty(this.phone, '请输入手机号') ||
                    formCheck.phoneRight(this.phone, '请输入正确的手机号码') ||
                    formCheck.isNonEmpty(this.code, '请输入验证码') ||
                    formCheck.checkeCode(this.code, '请检查验证码是否是纯数字~')

                if (errorMsg) {
                    this.$toast(errorMsg)
                    return
                }
                //账号密码登录
                this.$toast.loading({
                    message: '登录中...',
                    forbidClick: true
                })
				
                //调用快捷登录
                try {
					
					let countryCode = '+86'
                    let res = await oauthService.wechatQuickLogin(this.phone, this.code, countryCode, this.inviteCode, 'NORMAL')
                    if (!res.success) {
                        this.$toast(res.msg)
                        return
                    }
                    this.$toast({
                        message: '登录成功',
                        forbidClick: true
                    })

                    // 判断是不是有绑定qrCode
                    const qrCode = sessionStorage.getItem('qrCode')
                    if (qrCode) {
                        oauthApi
                            .bindRelationshipByQRCode({
                                qrCodeNumber: qrCode
                            })
                            .then((res) => {
                                if (!res.success) {
                                    this.$toast(res.msg)
                                    return
                                }
                                sessionStorage.removeItem('qrCode')
                            })
                            .catch((err) => {
                                sessionStorage.removeItem('qrCode')
                            })
                    }

                    // 判断用户是否需要立即补充用户信息
                    try {
      //                   const response = await this.getSetupInfo()
						// this.$store.commit('setupInfo', response);
						this.$store.dispatch('setupInfo');
						let response = this.$store.state.curUpInfo
                        if (response.result) {
                            this.$dialog
                                .confirm({
                                    title: '提示',
                                    showCancelButton: false,
                                    message: '您未完善个人信息，请前往完善个人信息'
                                })
                                .then(() => {
                                    this.$router.replace({ name: 'security', query: { need: 'finish', redirect: this.$route.query.redirect } })
                                })
                                .catch(() => {
                                    // on cancel
                                })
                        } else {
                            this.$route.query.redirect ? this.$router.replace(this.$route.query.redirect) : this.$router.replace('index')
                        }
                    } catch (err) {
                        this.$toast(error.msg)
                    }
                } catch (error) {
                    this.$toast({
                        message: error.msg
                    })
                }
            }
        },

        //第三方登录
        oauthLogin(provider) {
            this.$toast.loading({ mask: true, message: '正在登陆...' })
            oauthService.oauthLogin(provider).then((res) => {
                this.oauthLoginStatus2 = true
                if (res.success) {
                    this.$toast(res.msg)
                    if (res.status == 1) {
                        //如果验证通过，并已关联第三方，从什么页面过来的就跳回什么页面去
                        this.oauthLoginStatus2 = false
                        if (this.$route.query.redirect == undefined || this.$route.query.redirect == '/login') {
                            this.$router.replace('index')
                        } else {
                            this.$router.replace(this.$route.query.redirect)
                        }
                    } else if (res.status == 2) {
                        //如果验证通过，但未关联第三方，需要绑定账号！跳转至绑定手机号页面(注册)
                        let bindingIfo = {
                            passportIdKey: res.passportIdKey,
                            platform: res.platform
                        }
                        passport.setPassportIdKey(bindingIfo.passportIdKey)
                        this.$router.replace({ path: `/bindingPhone` })
                    } else {
                        //如果验证不通过，返回登录页面
                        this.oauthLoginStatus2 = false
                        this.$router.replace({ path: `/login` })
                    }
                } else {
                    this.oauthLoginStatus2 = false
                    this.$toast(res.msg)
                    if (res.networkErr) {
                        this.$router.replace('index') //如果网络请求异常，跳转至首页
                    } else {
                        this.$router.replace({ path: `/login` }) //如果验证没通过，跳转至登录页面
                    }
                }
            })
        },
        //去阅读注册协议
        goAgreement() {
            this.$router.push({
                path: `/agreement`,
                query: {
                    type: 'USER_REG_TYPE'
                }
            })
        },

        // 填入邀请码
        fillInviteCode() {
            this.inviteCode = this.inviteSetting.defaultInvitationCode
        },

        // 获取配置
        getInvRelationShipSetting() {
            InvRelationShipSetting({
                mobilePhone: this.phone
            }).then((res) => {
                if (!res.success) {
                    this.$toast(res.msg)
                    return
                }

                this.inviteSetting = res.result
            })
        },
		backHome() {
			this.$router.replace({
			    path: `/index`,
			})
		},
    },
    computed: {
        ...mapState(['themes'])
    }
}
</script>

<style src="../../assets/css/style/login-style.css" scoped></style>
<style src="../../assets/css/style/b-btn.css" scoped></style>
<style src="../../assets/css/login.css" scoped></style>
<style scoped>
.captcha {
    padding: 0 15px;
    /* position: absolute; */
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    flex-direction: column;
    width: 100%;
    box-sizing: border-box;
    background: #fff;
}
.captcha .login {
    flex: 1;
    min-height: 420px;
}
.captcha .container {
    flex: 1;
    min-height: 420px;
}
.captcha h3 {
    margin: 20px 0 14px;
    font-size: 24px;
    font-weight: 500;
    color: #333;
    line-height: 24px;
}
.captcha .safe-tips {
    font-size: 14px;
    color: #999;
    margin-top: 20px;
    line-height: 14px;
}
.captcha .login-box {
    padding: 21px 0 10px;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    align-items: center;
    font-size: 14px;
}
.captcha .login-box .country {
    padding-right: 10px;
    margin-right: 10px;
    color: #333;
    position: relative;
}
.captcha .login-box .country::after {
    display: block;
    content: ' ';
    width: 1px;
    height: 14px;
    background: #e5e5e5;
    position: absolute;
    top: 50%;
    margin-top: -7px;
    right: 0;
}
.captcha .cell {
    position: relative;
    display: flex;
    width: 100%;
    overflow: hidden;
    box-sizing: border-box;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
    padding: 10px 15px;
}
.captcha .phone {
    flex: 1;
    background: none;
    padding: 0;
}
.captcha .cell .field__body input {
    font-size: 14px;
    line-height: 1em;
    padding: 4px 0;
    height: 24px;
    border: 0;
    margin: 0;
    display: block;
    color: #323233;
    box-sizing: border-box;
    background-color: transparent;
}
.captcha .cell .login-btn {
    display: inline-block;
    color: #38f;
    font-size: 14px;
    margin-left: auto;
}
.field__body {
    display: flex;
    align-items: center;
}
.checke-type {
    font-size: 12px;
    color: #38f;
    line-height: 12px;
}
.checke-type .pass-btn {
    display: inline-block;
}
.checke-type .register-btn,
.checke-type .forget-pass-btn {
    display: inline-block;
    text-align: right;
    float: right;
    vertical-align: bottom;
}

/* .checke-type .forget-pass-btn:after {
    content: '|';
    width: 1px;
    height: 100%;
    color: #e5e5e5;
    display: inline-block;
    margin: 0 10px;
    vertical-align: bottom;
} */
.countdown {
    font-size: 12px;
    color: #ccc;
}
.login__footer {
    font-size: 12px;
    color: #bbb;
    line-height: 14px;
    text-align: center;
    margin: 25px 0;
}

.captcha .container {
    /* flex: 1; */
    /* min-height: 500px; */
}
</style>

<style>
._nc .stage1 .slider {
    height: 42px !important;
    box-shadow: none;
    border: 1px solid #4eae31;
    background-color: #fff;
}
._nc .stage1 .button {
    left: -1px;
    top: -1px;
    background-color: #5fc221;
}
._nc .stage1 .track div,
._nc .stage1 .label,
._nc .stage1 .button,
._nc .stage1 {
    line-height: 42px;
    height: 42px;
}
._nc .stage1 .track div {
    color: #fff !important;
}
._nc .stage1 .bg-green {
    background: rgba(7, 193, 96, 0.2) !important;
}
</style>
